package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.component.MinioProperties;
import com.atguigu.gmall.product.service.UploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/7 22:19
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProperties minioProperties;


    @Override
    public String uploadToMinio(MultipartFile file) {
        try {
            String bucketName = minioProperties.getBucketName();
            String endpoint = minioProperties.getEndpoint();

            InputStream inputStream = file.getInputStream();
            String contentType = file.getContentType();
            String fileName = UUID.randomUUID().toString().replace("-","")+"_"+file.getOriginalFilename();
            PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
            options.setContentType(contentType);
            client.putObject(bucketName,fileName,inputStream,options);
            return endpoint+"/"+bucketName+"/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
